package com.zycfc.zsf.boot.job;

import com.dangdang.ddframe.job.reg.zookeeper.*;
import com.zycfc.zsf.boot.job.core.*;
import org.springframework.util.*;
import org.apache.curator.framework.recipes.cache.*;
import com.zycfc.zsf.boot.util.time.*;
import com.zycfc.zsf.boot.logback.util.*;
import org.slf4j.*;

public class ZsfJobSwitch
{
    private static final Logger log;
    private ZookeeperRegistryCenter zookeeperRegistryCenter;
    private String applicationName;
    private final String PATH;
    private String status;
    public static final String ON = "ON";
    public static final String OFF = "OFF";
    
    public ZsfJobSwitch(final ZookeeperRegistryCenter zookeeperRegistryCenter, final String applicationName) {
        this.zookeeperRegistryCenter = zookeeperRegistryCenter;
        this.applicationName = applicationName;
        this.PATH = String.format("/switch/%s", applicationName);
    }
    
    public void init() {
        NodeCache cache = null;
        try {
            this.initializeSwitch();
            cache = new NodeCache(this.zookeeperRegistryCenter.getClient(), this.PATH);
            cache.start();
            this.addListener(cache);
        }
        catch (Exception e) {
            ZsfJobSwitch.log.error(e.getMessage(), (Throwable)e);
        }
    }
    
    private void initializeSwitch() {
        final ZsfJobNodePath zsfJobNodePath = new ZsfJobNodePath(this.applicationName);
        final String onOff = this.zookeeperRegistryCenter.get(zsfJobNodePath.setSwitchNodePath());
        this.status = (StringUtils.isEmpty((Object)onOff) ? "ON" : onOff);
    }
    
    private void addListener(final NodeCache cache) {
        final NodeCacheListener listener = () -> {
            TraceUtil.beginLocalTrace("ZsfJobSwitch" + DateUtils.getCurDT() + DateUtils.getCurTM());
            try {
                if (cache.getCurrentData() != null) {
                    final String nodePath = cache.getCurrentData().getPath();
                    final String nodeValue = new String(cache.getCurrentData().getData());
                    ZsfJobSwitch.log.warn("zookeeper job switch Node changed: name path is [{}], value is [{}]", (Object)nodePath, (Object)nodeValue);
                    if ("OFF".equals(nodeValue)) {
                        this.status = "OFF";
                    }
                    else if ("ON".equals(nodeValue)) {
                        this.status = "ON";
                    }
                }
            }
            catch (Exception e) {
                ZsfJobSwitch.log.error("ZsfJob: ZsfJobSwitch failure, {}", (Object)e.getMessage(), (Object)e);
            }
            TraceUtil.endTrace();
        };
        cache.getListenable().addListener((Object)listener);
    }
    
    public String getStatus() {
        return this.status;
    }
    
    static {
        log = LoggerFactory.getLogger((Class)ZsfJobSwitch.class);
    }
}
